/*	GatherGas class definition.
 *
*/

#include "GatherGas.h"

void GatherGas::Enter()
{
	DEBUG_PRINT("GatherGas(%p) entering.\n", this);
}

void GatherGas::Execute()
{
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>* scvs;
	std::list<Geyser*>* geyserList;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		DEBUG_PRINT("GatherGas(%p) executing.\n", this);
		scvs = (*base)->GetUnitsByType(BWAPI::UnitTypes::Terran_SCV);
		DEBUG_PRINT("Grabbing worker list scvs(%p) of size %d.\n", scvs, scvs->size());
		geyserList = (*base)->GetGeysers();
		DEBUG_PRINT("Grabbing minerals list geyserList(%p) of size %d.\n", geyserList,geyserList->size());
		Geyser* geyserToHarvest = NULL;
		if(geyserList)
		{
			if(scvs->size() > 8)
			{
				for(std::list<BWAPI::Unit*>::iterator it = scvs->begin(); it != scvs->end(); it++)
				{
					if((*it)->isIdle() || (*it)->isGatheringMinerals() )
					{
						for(std::list<Geyser*>::iterator geyserIt = geyserList->begin(); geyserIt != geyserList->end(); geyserIt++)
						{
							if((*geyserIt)->refinery)
							{
								if((*geyserIt)->gathering < 3)
								{
									geyserToHarvest = *geyserIt;
									break;
								}
							}
						}
						if (geyserToHarvest)
						{
							geyserToHarvest->gathering++;
							DEBUG_PRINT("Sending scv(%p) to mine mineral(%p) that has %d mining.\n", (*it),geyserToHarvest,geyserToHarvest->gathering );
							(*it)->rightClick(geyserToHarvest->refinery);
							break;
						}
					}
				}
			}
		}
	}
	control->FinishWithSuccess();
}

void GatherGas::Exit()
{
	DEBUG_PRINT("Exiting GatherGas behavior.\n");
}

bool GatherGas::CheckConditions()
{
	DEBUG_PRINT("Checking GatherGas conditions.\n");
	std::list<Base*>* bases = BB->GetBases();
	std::list<BWAPI::Unit*>*	scvs;
	std::list<BWAPI::Unit*>*	refineries;
	for(std::list<Base*>::iterator base = bases->begin(); base != bases->end(); base++)
	{
		scvs = (*base)->GetUnitsByType(BWAPI::UnitTypes::Terran_SCV);
		refineries = (*base)->GetBuildingsByType(BWAPI::UnitTypes::Terran_Refinery);
		if(refineries)
		{
			for(std::list<BWAPI::Unit*>::iterator refinery = refineries->begin(); refinery != refineries->end(); refinery++)
			{
				if((*refinery)->isCompleted())
				{
					for(std::list<BWAPI::Unit*>::iterator it = scvs->begin(); it != scvs->end(); it++)
					{
						if((*it)->isIdle()|| (*it)->isGatheringMinerals() )
						{
							DEBUG_PRINT("Checking GatherGas conditions.  Found SCV.  Returning true.\n");
							return true;
						}
					}
				}
			}
		}
	}
	DEBUG_PRINT("Checking GatherGas conditions.  Did not find SCV.  Returning false.\n");
	return false;
}